/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Test;

import MNetSockets.DataChanel.DataClient;
import MNetSockets.DataChanel.IUDPDataReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author wcss
 */
public class UDPChannelCreate extends javax.swing.JFrame implements IUDPDataReader, Runnable {

    public DataClient dc = new DataClient(65343);
    private Boolean isRunTest = false;
    private Thread udpTest = null;
    private int udpTestCount = 100;
    private int currentTestIndex = 0;
    private long msgIndex = 0;

    /**
     * Creates new form UDPChannelCreate
     */
    public UDPChannelCreate() {
        initComponents();

        dc.receiveEvent = this;
        try {
            dc.start();
        } catch (Exception ex) {
            Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        String sss = "[\"110.210.28.92\", 43805]".toString().replace("[", "").replace("\"", "").replace("]", "");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblState = new javax.swing.JLabel();
        lblUDPTestCount = new javax.swing.JLabel();
        btnServer = new javax.swing.JButton();
        btnClient = new javax.swing.JButton();
        btnStop = new javax.swing.JButton();
        txtServerAddress = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblState.setText("jLabel1");

        lblUDPTestCount.setText("jLabel1");

        btnServer.setText("此节点为提供者");
        btnServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnServerActionPerformed(evt);
            }
        });

        btnClient.setText("此节点为下载者");
        btnClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClientActionPerformed(evt);
            }
        });

        btnStop.setText("停止");
        btnStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStopActionPerformed(evt);
            }
        });

        txtServerAddress.setText("108.171.204.250");

        btnSend.setText("发送测试消息");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblUDPTestCount, javax.swing.GroupLayout.PREFERRED_SIZE, 835, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblState, javax.swing.GroupLayout.PREFERRED_SIZE, 835, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(64, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnServer)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnClient)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSend)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtServerAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(lblState, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblUDPTestCount, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnServer, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnClient, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnStop, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtServerAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, 65, Short.MAX_VALUE)))
                .addGap(66, 66, 66))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnServerActionPerformed
        // TODO add your handling code here:
        sendUDPMsg(txtServerAddress.getText().trim(), "saveserver");
        clientType = "keepconnection";
        recordPort = 0;
        recordAddress = "";
        this.startTest();
        this.btnClient.setEnabled(false);
        this.btnServer.setEnabled(false);
    }//GEN-LAST:event_btnServerActionPerformed

    private void btnClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClientActionPerformed
        // TODO add your handling code here:
        sendUDPMsg(txtServerAddress.getText().trim(), "saveclient");
        clientType = "client";
        recordPort = 0;
        recordAddress = "";
        
        try 
        {
            Thread.sleep(50);
        } catch (InterruptedException ex) {
            Logger.getLogger(UDPChannelCreate.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        sendUDPMsg(txtServerAddress.getText().trim(), "getserver");
    }//GEN-LAST:event_btnClientActionPerformed

    private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed
        // TODO add your handling code here:
        this.stopTest();
    }//GEN-LAST:event_btnStopActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        // TODO add your handling code here:
        sendUDPMsg(txtServerAddress.getText().trim(), 65343, "fdafdsfafdfafddas" + "-MsgIndex:" + getMsgIndex());
        sendUDPMsg("10.11.241.79", 65343, "aaaaaaaaaa" + "-MsgIndex:" + getMsgIndex());
    }//GEN-LAST:event_btnSendActionPerformed
    private String server;
    private int port = 0;
    private String msg;

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UDPChannelCreate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UDPChannelCreate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UDPChannelCreate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UDPChannelCreate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new UDPChannelCreate().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClient;
    private javax.swing.JButton btnSend;
    private javax.swing.JButton btnServer;
    private javax.swing.JButton btnStop;
    private javax.swing.JLabel lblState;
    private javax.swing.JLabel lblUDPTestCount;
    private javax.swing.JTextField txtServerAddress;
    // End of variables declaration//GEN-END:variables
//    private int remotePorts = 0;
//    private String remoteAddresss = "";
    private int recordPort = 0;
    private String recordAddress = "";
    private String clientType = "";

    public long getMsgIndex() {
        msgIndex++;
        return msgIndex;
    }

    public void sendUDPMsg(String ip, String content) {
        try {
            dc.send(new InetSocketAddress(ip, 65343), content + "-MsgIndex:" + getMsgIndex());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void sendUDPMsg(String ip, int port, String content) {
        try {
            dc.send(new InetSocketAddress(ip, port), content + "-MsgIndex:" + getMsgIndex());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void startTest() {
        currentTestIndex = 0;
        isRunTest = true;
        udpTest = new Thread(this);
        udpTest.setDaemon(true);
        udpTest.start();
    }

    public void stopTest() {
        isRunTest = false;
        //this.lblUDPTestCount.setText("打洞测试停止！");
    }

    @Override
    public void dataRead(Object o, SocketAddress sa, Object o1) {
        String curIP = ((InetSocketAddress) sa).getAddress().getHostAddress();
        System.out.println("消息到达 IP:" + curIP + ",端口：" + ((InetSocketAddress) sa).getPort() + " 内容：" + o1.toString());
        this.lblState.setText("消息到达：" + curIP + " " + o1.toString());
        String cmd = o1.toString().replace("{@@}", "").replace("{##}", "");

//        if (o1.toString().contains("[")) {
//            //["110.210.28.92", 43805]
//            String sss = cmd.toString().replace("[", "").replace("\"", "").replace("]", "");
//            String[] team = sss.split(",");
//            System.out.println(sss);
//            server = team[0];
//            port = Integer.parseInt(team[1].trim());
//            msg = "createchanel";
//        }

//        if (o1.toString().contains("toclient:")) {
//            recordAddress = cmd.replace("toclient:", "").split("><")[0];
//            recordPort = Integer.parseInt(cmd.replace("toclient:", "").split("><")[1]);
//
////            if (remotePorts <= 0 && remoteAddresss != null && remoteAddresss.isEmpty()) {
////                remoteAddresss = recordAddress;
////                remotePorts = recordPort;
////            }
//
//            try {
//                dc.send(new InetSocketAddress(recordAddress, recordPort), "x1x2");
//            } catch (Exception ex) {
//                Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
//            }
//
//            //sendUDPMsg(txtServerAddress.getText().trim(), "toserver");
//        }
//
//        if (o1.toString().contains("toserver:")) {
//            recordAddress = cmd.replace("toserver:", "").split("><")[0];
//            recordPort = Integer.parseInt(cmd.replace("toserver:", "").split("><")[1]);
//
////            if (remotePorts <= 0 && remoteAddresss != null && remoteAddresss.isEmpty()) {
////                remoteAddresss = recordAddress;
////                remotePorts = recordPort;
////            }
//
//            try {
//                dc.send(new InetSocketAddress(recordAddress, recordPort), "x3x4");
//            } catch (Exception ex) {
//                Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
//            }
//
//            //sendUDPMsg(txtServerAddress.getText().trim(), "toclient");
//        }
        
        if (cmd.contains("getaddress:"))
        {
            recordAddress = cmd.replace("getaddress:", "").split("><")[0].trim();
            recordPort = Integer.parseInt(cmd.replace("getaddress:", "").split("><")[1].trim());
            this.startTest();
            this.btnServer.setEnabled(false);
            this.btnClient.setEnabled(false);
        }

        if (o1.toString().contains("x1x2")) {

            this.stopTest();
            
            try {
                dc.send(sa, "x3x4");
                System.out.println("发送回应消息");
            } catch (Exception ex) {
                Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
            }

            this.lblUDPTestCount.setText("打洞成功！");
        }

        if (o1.toString().contains("x3x4")) {

//            try {
//                dc.send(sa, "x1x2");
//                System.out.println("发送回应消息");
//            } catch (Exception ex) {
//                Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
//            }

            this.stopTest();
            this.lblUDPTestCount.setText("打洞成功！");
        }
    }

    public void keepConnectionMethod()
    {
        sendUDPMsg(txtServerAddress.getText().trim(), "saveserver");
        try 
        {            
            Thread.sleep(5000);            
        } catch (InterruptedException ex) {
            Logger.getLogger(UDPChannelCreate.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void createUDPChannel()
    {
        if (recordPort > 0)
        {
            sendUDPMsg(recordAddress,recordPort,"x1x2");
            
            try 
            {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(UDPChannelCreate.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
    
    @Override
    public void run() {
        while (isRunTest) {
            currentTestIndex++;
            this.lblUDPTestCount.setText("正在进行第" + currentTestIndex + "次打滑尝试!");

            if (clientType.equals("keepconnection")) 
            {
                keepConnectionMethod();
            } else {
                createUDPChannel();
            }

//            //sendUDPMsg(server, port, msg);
//
//            try {
//                Thread.sleep(500);
//            } catch (InterruptedException ex) {
//                Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
//            }
        }
    }
}
